package com.richinfo.buddy.oauthserver.utils;

import java.io.OutputStream;
import java.nio.charset.Charset;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import com.alibaba.fastjson.JSONObject;


/**
* Created by WangXJ
* 2019-05-15 15:03
*/
public class WebUtils {
	
	private static final Logger logger = LoggerFactory.getLogger(WebUtils.class);
	
	
    public static void sendForbiddenError(HttpServletResponse response, Object result) {
        send(response, HttpStatus.FORBIDDEN, result);
    }

    @SuppressWarnings("deprecation")
    public static void send(HttpServletResponse response, HttpStatus status, Object result) {
        try (OutputStream out = response.getOutputStream()) {
            // response.send(status.value(), status.getReasonPhrase());
            response.setStatus(status.value(), status.getReasonPhrase());
            if (result != null) {
                response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);// 设置返回类型
                out.write(JSONObject.toJSONString(result).getBytes(getDefaultCharset()));// 输出
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
    
    public static String getDefaultCharsetString() {
        return "utf-8";
    }

    public static Charset getDefaultCharset() {
        return Charset.forName(getDefaultCharsetString());
    }
}
